using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

using KNCApp.Business;

namespace KNCApp.Port
{
    public class PortChecker
    {
        private string diagDirStr;
        
        public PortChecker()
        {
            diagDirStr = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar.ToString() + "Diagnostyka";
            if (!Directory.Exists(diagDirStr))
            {
                Directory.CreateDirectory(diagDirStr);
            }

        }

        public void Check()
        {
            List<PortHandler> pHandlers = new List<PortHandler>();
            List<DataLogger> dLoggers = new List<DataLogger>();
            string[] positions = SettingsMgr.GetAvailablePositions();
            PortHandler ph = null;
            DataLogger dl = null;
            string fName = "";
            foreach(string p in positions)
            {
                ph = new PortHandler(SettingsMgr.GetPort(p));
                fName = diagDirStr + Path.DirectorySeparatorChar.ToString() + p + ".log";
                dl = new DataLogger(fName);
                ph.StartReading("5", dl);
                pHandlers.Add(ph);
                dLoggers.Add(dl);
            }
            /*
            ph = new PortHandler(SettingsMgr.GetPressurePort());
            ph.BaudRate = 2400;
            fName = diagDirStr + Path.DirectorySeparatorChar.ToString() + "Pressure.log";
            dl = new DataLogger(fName);
            ph.StartReading("", dl);
            */

            Thread.Sleep(20000);

            foreach (PortHandler pHand in pHandlers)
            {
                pHand.Stop("x");
            }
            foreach (DataLogger dLog in dLoggers)
            {
                dLog.Close();
            }

            //ph.Stop("");
            //dl.Close();
        }
    }

    class DataLogger : IReceiver
    {
        private StreamWriter sw;
        
        public DataLogger(string fileName)
        {
            sw = File.CreateText(fileName);
        }

        public void Receive(string data)
        {
            sw.WriteLine(data);
            sw.Flush();
        }

        public void Close()
        {
            if(sw != null)
                sw.Close();
        }
    }
}
